<?php
/**
 * 清单
 */
class ListModule
{
	public function index()
	{
        global $_FANWE;
        
        $cateids = array();
        $sql = 'SELECT cate_id FROM '.FDB::table('wogu_list_session').' WHERE uid='.$_FANWE['uid'];
        $results = FDB::fetchAll($sql);
        foreach($results as $v) {
            $cateids[] = $v['cate_id'];
        }
        
        $sql = 'SELECT * FROM '.FDB::table('goods_category').' WHERE parent_id=0 AND cate_id!=1 AND cate_type IN(0,1,3) AND listshow=0';
        $cates = FDB::fetchAll($sql);
        $cateid = intval($_GET['cate']);
        $cateid = $cateid == 0 ? $cates[0]['cate_id'] : $cateid;
        $sql = 'SELECT * FROM '.FDB::table('goods_category').' WHERE parent_id='.$cateid.' AND cate_type IN(0,1,3) AND listshow=0';
        $subcates = FDB::fetchAll($sql);
        $iscomplete = true;
        foreach($subcates as $k => $subcate) {
            $subcates[$k]['format_links'] = array();
            if(!empty($subcate['links'])) {
                $linkinfo = explode("\r\n", $subcate['links']);
                foreach($linkinfo as $v) {
                    $subcates[$k]['format_links'][] = $v;
                }
            }
            
            if(!in_array($subcate['cate_id'], $cateids)) {
                $iscomplete = false;
            }
        }
        
        include template('page/list/list_index');
        display();
        exit;
	}
	
	public function doread() {
	    global $_FANWE;
	    
	    $id = intval($_GET['id']);
	    if($id) {
	        $sql = 'INSERT INTO '.FDB::table('wogu_list_session')." (cate_id,uid) VALUES({$id},{$_FANWE['uid']})";
	        FDB::query($sql);
	    }
	}
	
	public function submit() {
	    include_once(FANWE_ROOT.'./core/include/PHPExcel.php');
	    $chars = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
	    
        $cateid = intval($_POST['cate']);
        if(!$cateid) exit;
        $sql = 'SELECT * FROM '.FDB::table('goods_category').' WHERE parent_id='.$cateid.' AND cate_type=1';
        $subcates = FDB::fetchAll($sql);
        $objPHPExcel = new PHPExcel();		 
        $sheet = $objPHPExcel->setActiveSheetIndex(0);
        foreach($subcates as $k => $subcate) {
            $rownum = $k + 1;

            $sheet->setCellValue('A'.$rownum, $subcate['cate_name']);
            $sheet->setCellValue('B'.$rownum, $_POST['des'][$subcate['cate_id']]);
            if(!empty($subcate['links'])) {
                $linkinfo = explode("\r\n", $subcate['links']);
                $colindex = 2;
                foreach($linkinfo as $v) {
                    $arr = explode('|', $v);
                    $cellindex = $chars[$colindex].$rownum;
                    $objPHPExcel->getActiveSheet()->setCellValue($cellindex, $arr[0]);
                    $objPHPExcel->getActiveSheet()->getCell($cellindex)->getHyperlink()->setUrl($arr[1]);
                    $colindex++;
                }
            }
        }
        
        // Redirect output to a client’s web browser (Excel5)
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="清单.xls"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
        
        // If you're serving to IE over SSL, then the following may be needed
        header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
        header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header ('Pragma: public'); // HTTP/1.0
        
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
	}
	
	public function robot() {
	    global $_FANWE;
	    
	    // if($_FANWE['user']['user_type'] == 1) {
	    //     if($_FANWE['user']['bossid'] == 0)
     //            fHeader('location: '.FU('list/staff'));
     //        else
     //            fHeader('location: '.FU('list/workplan&sj=all'));
     //        exit;
	    // }
        if($_GET['getlast']){
            $sql = 'SELECT * FROM '.FDB::table('wogu_robot_logs').' WHERE uid='.$_FANWE['uid'].' order by id desc limit 1';
            $res = FDB::fetchFirst($sql);
            ajax_msg(0, $res);
            
        }
	    if($_POST['docomplete']) {
	        $id = intval($_POST['id']);
	        $completedids = empty($_FANWE['user']['robot_completed']) ? array() : explode(',', $_FANWE['user']['robot_completed']);
	        if(!in_array($id, $completedids)) {
	            array_push($completedids, $id);
	        }
	        $str = implode(',', $completedids);
	        $sql = 'UPDATE '.FDB::table('user').' SET robot_completed=\''.$str.'\' WHERE uid='.$_FANWE['uid'];
	        FDB::fetchFirst($sql);
	        exit;
	    } elseif($_POST['doask']) {
	        require FANWE_ROOT.'core/function/wogu.func.php';
            $ask = htmlspecialchars($_POST['ask'], ENT_QUOTES);
            $answer = getanswer($ask, intval($_POST['aid']), intval($_POST['tipid']));
            if($answer == '听不懂你说什么...') {
                FDB::insert('wogu_robot_unknow', array('uid' => $_FANWE['uid'], 'ask' => $ask));
            }
            //消息记录
            $id = FDB::insert('wogu_robot_logs', array('uid' => $_FANWE['uid'], 'ask' => $ask, 'answer' => addslashes($answer)),true);
            
            if($_POST['ajax']){
                //ajax_msg(0, $answer);
                    $sql = 'SELECT * FROM '.FDB::table('wogu_robot_logs').' WHERE uid='.$_FANWE['uid'].' order by id asc';
                    $res = FDB::query($sql);
                    while($log = FDB::fetch($res)) {
                        $day = date('Y-m-d');
                        $log['dateline'] = str_replace($day.' ', '', $log['dateline']);
                        $log['dateline'] = substr($log['dateline'], 0, strrpos($log['dateline'], ':'));
                        $logs[] = $log;
                    }
                    foreach ($logs as $k1 => $v1) {
                       if($v1['id']==$id){
                            //$newdata = $v;
                             ajax_msg(0, $v1);
                       }
                    }
                   
            }
            exit($answer);
	    }
	    
        $sql = 'SELECT * FROM '.FDB::table('goods_category').' WHERE parent_id=0 AND cate_id!=1 AND cate_type IN(0,1,3) AND listshow=0';
        $cates = FDB::fetchAll($sql);
        
        $sql = 'SELECT * FROM '.FDB::table('wogu_feedback_tags') . ' ORDER BY like_num DESC';
        $keywords = FDB::fetchAll($sql);
        $total = 0;
        foreach($keywords as $v) {
            $total += $v['like_num'];
        }
        $logs[0]['answer'] = '欢迎来到火锅君，看看火锅君能干嘛吧！';
        for($i = 0; $i < 5; $i++) {
            if(isset($keywords[$i])) {
                $keyword = $keywords[$i];
                $rate = intval($keyword['like_num'] / $total * 100);
                $logs[0]['answer'] .= '<p>'.$keyword['tagname'].'['.$rate.'%]</p>';
            }
        }
        $sql = 'SELECT * FROM '.FDB::table('wogu_robot_logs').' WHERE uid='.$_FANWE['uid'].' order by id asc';
        $res = FDB::query($sql);
        while($log = FDB::fetch($res)) {
            $day = date('Y-m-d');
            $log['dateline'] = str_replace($day.' ', '', $log['dateline']);
            $log['dateline'] = substr($log['dateline'], 0, strrpos($log['dateline'], ':'));
            $logs[] = $log;
        }
        //var_dump($logs);exit;
        if($_GET['ajax']){
            ajax_msg(0, $logs);
            
        }
        $keyword = '';
        include template('page/list/list_robot');
        display();
	}
	
	public function staff() {
	    global $_FANWE;
	    if($_POST['doinvite']) {
	        $uname = addslashes($_POST['uname']);
	        $userinfo = FDB::fetchFirst("SELECT * FROM ".FDB::table('user')." WHERE user_name='{$uname}'");
	        if(!empty($userinfo) && $userinfo['user_type'] == 1) {
	            $uid = $userinfo['uid'];
    	        $msg = "{$_FANWE['user']['user_name']}邀请您成为他的员工，<a href=\"/list.php?action=staff&inviteback&uid={$_FANWE['uid']}\">点击确定</a>";
    	        FDB::query("INSERT INTO ".FDB::table("sys_notice")." (uid, title, content, create_time) VALUES($uid,'员工邀请通知','{$msg}','".time()."')");
    	        FS('User')->setUserTips($uid, 6);
    	        showSuccess('提示', '邀请发送成功！', FU('list/staff'));
    	    }
	        
            showError('错误信息', '用户不存在或不是商家账号', $_SERVER['HTTP_REFERER']);
	    } elseif(isset($_GET['inviteback'])) {
	        $uid = intval($_GET['uid']);
    		
    		$r = FDB::fetchFirst("SELECT COUNT(*) AS total FROM ".FDB::table('wogu_mystaff')." WHERE uid={$uid} AND staffid={$_FANWE['uid']}");
    		if($r['total'] == 0)
    	        FDB::query("INSERT INTO ".FDB::table('wogu_mystaff')."(uid, staffid) VALUES($uid,{$_FANWE['uid']})", 'SILENT');
    	    FDB::query("UPDATE ".FDB::table("user")." SET bossid={$uid} WHERE uid={$_FANWE['uid']}");
    	    showSuccess('提示', '接受邀请成功！开始写工作计划吧~', FU('list/workplan'));
	    }

        $sql = 'SELECT * FROM '.FDB::table('goods_category').' WHERE parent_id=0 AND cate_id!=1 AND cate_type IN(0,1,3) AND listshow=0';
        $cates = FDB::fetchAll($sql);
        
        $where = 's.uid='.$_FANWE['uid'];
        $sql = 'SELECT COUNT(s.id) FROM '.FDB::table('wogu_mystaff').' s WHERE '.$where;
        $count = FDB::resultFirst($sql);
        $page_args = array();
        $pager = buildPage('list/'.ACTION_NAME,$page_args,$count,$_FANWE['page'],10);
        
        $sql = 'SELECT s.*,u.user_name FROM '.FDB::table('wogu_mystaff').' s LEFT JOIN '.FDB::table('user').' u ON s.staffid=u.uid WHERE '.$where.' ORDER BY s.id DESC LIMIT '.$pager['limit'];
        $staff_list = FDB::fetchAll($sql);
	    
        include template('page/list/list_staff');
        display();
	}
	
    
    public function workplan() {
        global $_FANWE;
        
        if($_POST['doadd']) {
            $title = htmlspecialchars(trim($_POST['title']));
            if(empty($title))
                showError('错误信息', '计划简介不能为空！', $_SERVER['HTTP_REFERER']);
            $content = trim($_POST['content']);
            $content = preg_replace(array('/\'/', '/<script[\s\S]+?\/script>/i'), array('&#039;',''), $content);
            if(empty($content))
                showError('错误信息', '计划内容不能为空！', $_SERVER['HTTP_REFERER']);
            $sj = strtotime($_POST['sj']);
            if(false === $sj)
                showError('错误信息', '请选择计划执行时间！', $_SERVER['HTTP_REFERER']);
            
            $staffid = intval($_POST['uid']);
            $uid = $staffid ? $staffid : $_FANWE['uid'];
            $id = FDB::insert('wogu_workplan', array('uid' => $uid, 'title' => $title, 'content' => $content, 'sj' => $sj), true);
            
            if($staffid) {
    	        $msg = "您的老板{$_FANWE['user']['user_name']}给你布置了一个任务，请<a href=\"/list.php?action=workplan&op=show&id={$id}\">查看</a>";
    	        FDB::query("INSERT INTO ".FDB::table("sys_notice")." (uid, title, content, create_time) VALUES($staffid,'发布任务通知','{$msg}','".time()."')");
                FS('User')->setUserTips($staffid, 6);
            } else {
                $bossid = $_FANWE['user']['bossid'];
    	        $msg = "您的员工{$_FANWE['user']['user_name']}发布了一个任务，请<a href=\"/list.php?action=workplan&op=show&id={$id}\">审核</a>";
    	        FDB::query("INSERT INTO ".FDB::table("sys_notice")." (uid, title, content, create_time) VALUES($bossid,'发布任务通知','{$msg}','".time()."')");
                FS('User')->setUserTips($bossid, 6);
            }
            
            showSuccess('提示', '计划发布成功！', '/list.php?action=workplan&op=show&id='.$id);
        }
        
        $sql = 'SELECT * FROM '.FDB::table('goods_category').' WHERE parent_id=0 AND cate_id!=1 AND cate_type IN(0,1,3) AND listshow=0';
        $cates = FDB::fetchAll($sql);
        
        if($_GET['op'] == 'add') {
            $uid = intval($_GET['uid']);
            include template('page/list/list_addworkplan');
        } elseif($_GET['op'] == 'setflag') {
            $id = intval($_GET['id']);
            $uid = intval($_GET['uid']);
            $flag = intval($_GET['flag']);
            FDB::update('wogu_workplan', array('flag' => $flag), array('id' => $id));
            if($uid == $_FANWE['uid']) { // 员工确认完成，给boss发通知
                $bossid = $_FANWE['user']['bossid'];
    	        $msg = "您的员工{$_FANWE['user']['user_name']}完成了一个任务，请<a href=\"/list.php?action=workplan&op=show&id={$id}\">审核</a>";
    	        FDB::query("INSERT INTO ".FDB::table("sys_notice")." (uid, title, content, create_time) VALUES($bossid,'完成任务通知','{$msg}','".time()."')");
                FS('User')->setUserTips($bossid, 6);
            }
            
            showSuccess('提示', '操作成功！', $_SERVER['HTTP_REFERER']);
        } elseif($_GET['op'] == 'show') {
            $id = intval($_GET['id']);
            $workplan = FDB::fetchFirst('SELECT * FROM '.FDB::table('wogu_workplan').' WHERE id='.$id);
            if(!$workplan)
                showError('错误信息', '该计划不存在！', $_SERVER['HTTP_REFERER']);
                
            //评论
    		$workplan['comments'] = FS('Workplan')->getShareCommentList($id,'0,10');
            include template('page/list/list_show_workplan');
        } else {
            if(isset($_GET['boss'])) {
                $sql = 'SELECT * FROM '.FDB::table('wogu_mystaff').' WHERE uid='.$_FANWE['uid'];
                $staffs = FDB::fetchAll($sql);
                if(empty($staffs)) showError('错误信息', '你还没有员工', $_SERVER['HTTP_REFERER']);
                $staffids = array();
                foreach($staffs as $v) {
                    $staffids[] = $v['staffid'];
                }
                $where = 'uid IN('.implode(',', $staffids).')';
                $sql = 'SELECT uid,user_name FROM '.FDB::table('user').' WHERE uid IN('.implode(',', $staffids).')';
                $rs = FDB::fetchAll($sql);
                foreach($rs as $v) {
                    $shownames[$v['uid']] = $v['user_name'];
                }
            } else {
                $uid = intval($_GET['uid']);
                $where = 'uid='.($uid ? $uid : $_FANWE['uid']);
                if($uid != $_FANWE['uid']) {
                    $sql = 'SELECT uid,user_name FROM '.FDB::table('user').' WHERE uid='.$uid;
                    $rs = FDB::fetchFirst($sql);
                    $shownames[$rs['uid']] = $rs['user_name'];
                }
            }
            $today = strtotime(date('Y-m-d'));
            $tomorrow = $today + 86400;
            $order = 'id DESC';
            if($_GET['sj'] == 'today') {
                $where .= ' AND (sj>='.$today.' AND sj<'.$tomorrow.')';
                $order = 'id ASC';
            } elseif($_GET['sj'] == 'tomorrow') {
                $where .= ' AND (sj>='.$tomorrow.' AND sj<'.($tomorrow+86400).')';
                $order = 'id ASC';
            }
            $sql = 'SELECT COUNT(id) FROM '.FDB::table('wogu_workplan').' WHERE '.$where;
            $count = FDB::resultFirst($sql);
            $page_args = array();
            $pager = buildPage('list/'.ACTION_NAME,$page_args,$count,$_FANWE['page'],10);
            
            $sql = 'SELECT * FROM '.FDB::table('wogu_workplan').' WHERE '.$where.' ORDER BY '.$order.' LIMIT '.$pager['limit'];
            $workplan_list = FDB::fetchAll($sql);
            include template('page/list/list_workplan');
        }
        display();
    }
    
    public function plan() {
        global $_FANWE;
        
        $config = include FANWE_ROOT . 'public/plan.php';

        if($_POST['doadd']) {
            $tip = htmlspecialchars(trim($_POST['tip']));
            if(empty($tip))
                exit('tip empty');
            
            if(empty($_POST['dateline']))
                exit('dateline empty');
                
            if(empty($_POST['ids']))
                exit('ids empty');

            $dateline = strtotime($_POST['dateline']);
            $list_id = FDB::insert('wogu_plan_list', array(
                'uid' => $_FANWE['uid'],
                'dateline' => $dateline,
                'tip' => $tip,
                'ampm' => intval($_POST['ampm'])
            ), true);
            
            foreach($_POST['ids'] as $v) {
                list($pid, $myid) = explode('|', $v);
                if( ($pid == -1 && !isset($config[$myid])) || ($pid != -1 && (!isset($config[$pid]) || !isset($config[$pid]['children'][$myid]))) )
                    exit('error arg');
                $item = $pid == -1 ? $config[$myid] : $config[$pid]['children'][$myid];
                if(!$item)
                    exit('error arg');
                FDB::insert('wogu_plan_items', array(
                    'list_id' => $list_id,
                    'pid' => $pid,
                    'myid' => $myid,
                    'dateline' => $dateline,
                    'uid' => $_FANWE['uid'],
                    'type' => $item['type']
                ));
            }
            exit('ok');
        } elseif($_POST['docomp']) {
            $itemid = intval($_POST['itemid']);
            if(!$itemid) exit;
            if(FDB::update('wogu_plan_items', array('flag' => 1), array('id' => $itemid)))
                exit('1');
            exit;
        } elseif($_POST['dobindshop']) {
            $itemid = intval($_POST['itemid']);
            if(!$itemid) exit;
            list($shopid, $orderid) = explode('|', $_POST['ids']);
            if(!$shopid || !$orderid) exit;
            $sql = 'SELECT * FROM '.FDB::table('wogu_order').' WHERE id='.$orderid;
            $orderinfo = FDB::fetchFirst($sql);
            if(!$orderinfo) exit;
            $paystep = $orderinfo['pay_mulit'] == 1 ? $orderinfo['paystep'] : 0;
            FDB::update('wogu_order', array('plan_itemid' => $itemid), array('id' => $orderid));
            if(FDB::update('wogu_plan_items', array('shopid' => $shopid, 'orderid' => $orderid, 'paystep' => $paystep), array('id' => $itemid)))
                exit('1');
            exit;
        } elseif($_POST['docompact']) {
            $id = intval($_POST['id']);
            if(!$id) exit;
            $itemid = intval($_POST['itemid']);

            $sql = 'SELECT * FROM '.FDB::table('wogu_plan_items').' WHERE id='.$id;
            $v = FDB::fetchFirst($sql);
            if(!$v) exit;
            $ampm = intval($_POST['ampm']);
            
            $item = $v['pid'] == -1 ? $config[$v['myid']] : $config[$v['pid']]['children'][$v['myid']];
            $data = empty($v['data']) ? array() : unserialize($v['data']);
            $data[$itemid] = array(
                'dateline' => time()
            );
            $flag = count($data) == count($item['items'][$ampm]) ? 1 : 0;
            if(FDB::update('wogu_plan_items', array('data' => serialize($data), 'flag' => $flag), array('id' => $id)))
                exit('1');
            exit;
        } elseif($_POST['dopay']) {
            $id = intval($_POST['id']);
            if(!$id) exit;
            $paystep = intval($_POST['paystep']);
            if(FDB::update('wogu_plan_items', array('paystep' => $paystep), array('id' => $id))) {
                require FANWE_ROOT.'core/function/wogu.func.php';
                dopay($id, $paystep);
//                $sql = 'SELECT * FROM '.FDB::table('wogu_plan_items').' WHERE id='.$id;
//                $item = FDB::fetchFirst($sql);
//                $sql = 'SELECT * FROM '.FDB::table('wogu_order').' WHERE id='.$item['orderid'];
//                $order = FDB::fetchFirst($sql);
//                if($paystep == 1) {
//                    $money = $order['total_fee'] * 0.3;
//                    $msg = "买家{$_FANWE['user']['user_name']}向您支付30%的定金（订单号:{$order['orderid']}），共计{$money}元！";
//                } elseif($paystep == 2) {
//                    $money = $order['total_fee'] * 0.8;
//                    $msg = "买家{$_FANWE['user']['user_name']}向您支付80%的费用（订单号:{$order['orderid']}），共计{$money}元！";
//                    $sql = 'UPDATE '.FDB::table('user').' SET rmb=rmb+'.$money.' WHERE uid='.$item['shopid'];
//                    FDB::query($sql);
//                } elseif($paystep == 3) {
//                    $msg = "买家{$_FANWE['user']['user_name']}已支付全部费用（订单号:{$order['orderid']}），共计{$order['total_fee']}元！";
//                    $money = $order['total_fee'] * 0.2;
//                    $sql = 'UPDATE '.FDB::table('user').' SET rmb=rmb+'.$money.' WHERE uid='.$item['shopid'];
//                    FDB::query($sql);
//                }
//
//                FDB::query("INSERT INTO ".FDB::table("sys_notice")." (uid, title, content, create_time) VALUES({$item['shopid']},'付款通知','{$msg}','".time()."')");
//                FS('User')->setUserTips($item['shopid'], 6);
                exit('1');
            }
            
            exit;
        } elseif($_POST['dounpay']) {
            $id = intval($_POST['id']);
            if(!$id) exit;
            $flag = intval($_POST['flag']);
            if($flag == 1) {
                $sql = 'SELECT * FROM '.FDB::table('wogu_plan_items').' WHERE id='.$id;
                $item = FDB::fetchFirst($sql);
                if(!$item) exit;

                $sql = 'SELECT * FROM '.FDB::table('wogu_unpay').' WHERE itemid='.$id;
                $tmp = $unpayinfo = FDB::fetchFirst($sql);

                $reason = intval($_POST['reason']);
                $money = intval($_POST['money']);
                if($money <= 0) showError('错误信息', '退款金额不正确！', $_SERVER['HTTP_REFERER']);
                $intro = htmlspecialchars($_POST['intro']);
                if(empty($intro)) showError('错误信息', '请输入退款说明！', $_SERVER['HTTP_REFERER']);
                $data = array(
                    'itemid' => $id,
                    'reason' => $reason,
                    'money' => $money,
                    'intro' => $intro,
                );
                if(!empty($_FILES['pic']) && (!$tmp || empty($tmp['pic1']) || empty($tmp['pic2']) || empty($tmp['pic3']))) {
                    $whitelist = array('jpg', 'jpeg', 'png', 'gif');
                    $dir = './public/unpayimgs/'.$id;
                    if(!is_dir($dir)) mkdir($dir, 0777, true);
                    $pics = $_FILES['pic'];
                    foreach ($pics['name'] as $k => $name) {
                        $find = false;
                        for($i = 1; $i <= 3; $i++) {
                            if(empty($tmp['pic'.$i])) {
                                $key = 'pic'.$i;
                                $find = true;
                            }
                        }
                        if(!$find) break;
                        $extension = pathinfo($name, PATHINFO_EXTENSION);
                        if($pics['size'][$k] > 0 && $pics['error'][$k] == 0 && in_array($extension, $whitelist)) {
                            $distname = $dir .'/'.$key.'.'.$extension;
                            if(move_uploaded_file($pics['tmp_name'][$k], $distname)) {
                                $tmp[$key] = $data[$key] = '/public/unpayimgs/'.$id.'/'.$key.'.'.$extension;
                            }
                        }
                    }
                }

                if($unpayinfo)
                    FDB::update('wogu_unpay', $data, array('itemid' => $id));
                else
                    FDB::insert('wogu_unpay', $data);
            }

            FDB::update('wogu_plan_items', array('unpay' => $flag), array('id' => $id));
            if($flag == 1)
                showSuccess('提示信息', '提交成功！', '/list.php?action=plan&op=showitem&itemid='.$id);
            else
                exit('1');
        }
        
        $sql = 'SELECT * FROM '.FDB::table('goods_category').' WHERE parent_id=0 AND cate_id!=1 AND cate_type IN(0,1,3) AND listshow=0';
        $cates = FDB::fetchAll($sql);
        
        if($_GET['op'] == 'add') {
            include template('page/list/list_addplan');
        } elseif($_GET['op'] == 'show') {
            $id = intval($_GET['id']);
            $sql = 'SELECT * FROM '.FDB::table('wogu_plan_list').' WHERE id='.$id.' AND uid='.$_FANWE['uid'];
            $pl = FDB::fetchFirst($sql);
            if(!$pl) exit;
            $sql = 'SELECT * FROM '.FDB::table('wogu_plan_items').' WHERE list_id='.$id;
            $items = FDB::fetchAll($sql);
            $pitems = array();
            foreach($items as $v) {
                $item = $v['pid'] == -1 ? $config[$v['myid']] : $config[$v['pid']]['children'][$v['myid']];
                $item['item_id'] = $v['id'];
                $item['flag'] = $v['flag'];
                if($v['type'] == 'shop' && $v['shopid'] > 0) {
                    $sql = 'SELECT * FROM '.FDB::table('user').' WHERE uid='.$v['shopid'];
                    $tmp = FDB::fetchFirst($sql);
                    $item['shopname'] = $tmp['user_name'];
                    $item['isstop'] = $v['isstop'];
                    $item['unpay'] = $v['unpay'];
                }
                
                if($v['pid'] == -1)
                    $pitems[$v['myid']] = $item;
                else {
                    if(!isset($pitems[$v['pid']])) {
                        $pitems[$v['pid']] = $config[$v['pid']];
                    }
                    $pitems[$v['pid']]['children'][$v['myid']] = $item;
                }
            }

            include template('page/list/list_showplan');
        } elseif($_GET['op'] == 'showitem') {
            $itemid = intval($_GET['itemid']);
            if(!$itemid) exit;
            $sql = 'SELECT * FROM '.FDB::table('wogu_plan_items').' WHERE id='.$itemid;
            $v = FDB::fetchFirst($sql);
            if(!$v) exit;
            $sql = 'SELECT * FROM '.FDB::table('wogu_plan_list').' WHERE id='.$v['list_id'];
            $pl = FDB::fetchFirst($sql);
            $item = $v['pid'] == -1 ? $config[$v['myid']] : $config[$v['pid']]['children'][$v['myid']];
            $item['item_id'] = $v['id'];
            $item['data'] = empty($v['data']) ? array() : unserialize($v['data']);
            $item['flag'] = $v['flag'];
            if($item['type'] == 'shop') {
                $item['shopid'] = $v['shopid'];
                $item['paystep'] = $v['paystep'];
                $item['isstop'] = $v['isstop'];
                $item['unpay'] = $v['unpay'];
                $item['orderid'] = $v['orderid'];
                if(!$v['shopid']) {
                    $sql = 'SELECT * FROM '.FDB::table('wogu_order').' WHERE userid='.$_FANWE['uid'].' AND flag>0 ORDER BY id DESC';
                    $res = FDB::query($sql);
                    while($r = FDB::fetch($res)) {
                        $order_list[] = $r;
                        $shopids[] = $r['shopid'];
                    }
                    if(!empty($shopids)) {
                        $shopids = array_unique($shopids);
                        $sql = 'SELECT * FROM '.FDB::table('user').' WHERE uid IN('.implode(',', $shopids).')';
                        $res = FDB::query($sql);
                        while($r = FDB::fetch($res)) {
                            $shopinfos[$r['uid']] = $r;
                        }
                    }
                } else {
                    $sql = 'SELECT * FROM '.FDB::table('user').' WHERE uid='.$v['shopid'];
                    $shopinfo = FDB::fetchFirst($sql);
                    $sql = 'SELECT * FROM '.FDB::table('wogu_order').' WHERE id='.$v['orderid'];
                    $orderinfo = FDB::fetchFirst($sql);
                }
                $sql = 'SELECT * FROM '.FDB::table('wogu_unpay').' WHERE itemid='.$itemid;
                $unpayinfo = FDB::fetchFirst($sql);
                include template('page/list/list_showitem_shop');
            } else {
                $colors = array('#ccffcc','#99ffcc','#33ff99','#99cc99','#33cc99','#669966','#009966','#336633');
                $colorid = 0;
                foreach($item['items'][$pl['ampm']] as $k => $v) {
                    if($k - 1 < 0 || $v['sj'] != $item['items'][$pl['ampm']][$k - 1]['sj']) {
                        $item['items'][$pl['ampm']][$k]['bgcolor'] = $colors[$colorid];
                        $colorid++;
                    } else {
                        $item['items'][$pl['ampm']][$k]['bgcolor'] = $item['items'][$pl['ampm']][$k - 1]['bgcolor'];
                    }
                    $item['items'][$pl['ampm']][$k]['sjtip'] = strpos($v['sj'], ':') === false ? '提前'.$v['sj'].'天' : '当天'.$v['sj'];
                }
                include template('page/list/list_showitem_act');
            }
        }  elseif($_GET['op'] == 'unpay') {
            $itemid = intval($_GET['id']);
            if(!$itemid) exit;
            $sql = 'SELECT * FROM '.FDB::table('wogu_plan_items').' WHERE id='.$itemid;
            $v = FDB::fetchFirst($sql);
            if(!$v) exit;

            $sql = 'SELECT * FROM '.FDB::table('wogu_unpay').' WHERE itemid='.$itemid;
            $unpayinfo = FDB::fetchFirst($sql);

            $sql = 'SELECT * FROM '.FDB::table('wogu_order').' WHERE id='.$v['orderid'];
            $orderinfo = FDB::fetchFirst($sql);
            $max_money = ($orderinfo['paystep'] == 1 ? 0.3 : 0.8) * $orderinfo['total_fee'];

            $num = 0;
            for($i = 1; $i <=3; $i++) {
                if(!empty($unpayinfo['pic'.$i])) $num++;
            }
            include template('page/list/list_unpay');
        } elseif($_GET['op'] == 'delunpaypic') {
            $id = intval($_GET['id']);
            if(!$id) exit;
            $sql = 'SELECT * FROM '.FDB::table('wogu_unpay').' WHERE id='.$id;
            $unpayinfo = FDB::fetchFirst($sql);
            if(!$unpayinfo) exit;
            if(!empty($unpayinfo[$_GET['key']])) {
                unlink('./'.$unpayinfo[$_GET['key']]);
                $sql = 'UPDATE '.FDB::table('wogu_unpay').' SET '.$_GET['key'].'=\'\' WHERE id='.$id;
                FDB::query($sql);
            }
            showSuccess('提示信息', '删除成功！', $_SERVER['HTTP_REFERER']);
        } else {
            $where = 'uid='.$_FANWE['uid'];
            $sql = 'SELECT COUNT(id) FROM '.FDB::table('wogu_plan_list').' WHERE '.$where;
            $count = FDB::resultFirst($sql);
            $page_args = array();
            $pager = buildPage('list/'.ACTION_NAME,$page_args,$count,$_FANWE['page'],10);
            
            $sql = 'SELECT * FROM '.FDB::table('wogu_plan_list').' WHERE '.$where.' ORDER BY id DESC LIMIT '.$pager['limit'];
            $plan_list = FDB::fetchAll($sql);
            include template('page/list/list_plan');
        }
        display();
    }
    
    public function lists() {
        global $_FANWE;
        
        $sql = 'SELECT * FROM '.FDB::table('wogu_lists_session').' WHERE uid='.$_FANWE['uid'];
        $session = FDB::fetchFirst($sql);
        if($session) {
            $session['complete'] = unserialize($session['complete']);
            $session['status'] = unserialize($session['status']);
        } else {
            $sql = 'INSERT INTO '.FDB::table('wogu_lists_session').' (uid) VALUES('.$_FANWE['uid'].')';
            FDB::query($sql);
        }

        if($_GET['op'] == 'setstatus') {
            $index = intval($_GET['index']);
            $status = intval($_GET['status']);
            $session['status'][$index] = $status;
            $sql = 'UPDATE '.FDB::table('wogu_lists_session').' SET status=\''.serialize($session['status']).'\' WHERE uid='.$_FANWE['uid'];
            FDB::query($sql);
            exit;
        } elseif($_GET['op'] == 'setcomplete') {
            $index = intval($_GET['index']);
            $session['complete'][$index] = 1;
            $sql = 'UPDATE '.FDB::table('wogu_lists_session').' SET complete=\''.serialize($session['complete']).'\' WHERE uid='.$_FANWE['uid'];
            FDB::query($sql);
            exit;
        }
        
        $lists = include FANWE_ROOT . 'public/lists.php';
        $complete = true;
        foreach($lists as $k => $v) {
            if(!isset($session['complete'][$k])) {
                $complete = false;
                break;
            }
        }

        $sql = 'SELECT * FROM '.FDB::table('goods_category').' WHERE parent_id=0 AND cate_id!=1 AND cate_type IN(0,1,3) AND listshow=0';
        $cates = FDB::fetchAll($sql);
        include template('page/list/list_lists');
        display();
    }
}
function ajax_msg($error, $data = '') {
    $arr = array(
        'error' => $error,
    );

    if($data) {
        $arr['data'] = $data;
    }

    exit(json_encode($arr));
}